package me.numark.fragments;


import android.content.ContentValues;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.R;
import me.numark.model.Feed;
import me.numark.model.FeedListResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.FeedListItemViewHolder;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class NewsFeedFragment extends Fragment implements
        AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView mList;

    private FeedAdapter mAdapter;

    private int mFeedType;

    private boolean isFirstLoad = false;

    public static final String TYPE = "is_timeline";

    public static final int TYPE_TIMELINE = 0;

    public static final int TYPE_MINE = 1;

    public static final int TYPE_HOT = 2;

    public static final int TYPE_OTHERS = 3;

    public static final String USER_ID = "user_id";

    private String mUserId;

    @InjectView(R.id.title)
    TextView titleView;

    @InjectView(R.id.header)
    View headerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_feed, container, false);
        ButterKnife.inject(this, view);
        mList = (PullToRefreshListView) view.findViewById(R.id.ptr_list);
        mList.setOnRefreshListener(this);
        mAdapter = new FeedAdapter();
        mList.setAdapter(mAdapter);
        mFeedType = getArguments().getInt(TYPE);
        if (mFeedType == TYPE_OTHERS) {
            mUserId = getArguments().getString(USER_ID);
        }
        mFeedType = getArguments().getInt(TYPE);
        mList.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        switch (mFeedType) {
            case TYPE_TIMELINE:
                titleView.setText(R.string.attentions);
                break;
        }
        if (getParentFragment() != null)
            headerView.setVisibility(View.GONE);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        loadFeeds(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        loadFeeds(mAdapter.getCount());
    }

    private void finishLoading() {
        mList.postDelayed(new Runnable() {
            @Override
            public void run() {
                mList.onRefreshComplete();
            }
        }, 100);
    }

    private class FeedAdapter extends BaseAdapter {

        Date today, yesterday, year;

        public FeedAdapter() {
            super();
            Date[] dates = Utils.getMarkDate();
            today = dates[0];
            yesterday = dates[1];
            year = dates[2];
        }

        @Override
        public int getCount() {
            return feeds.size();
        }

        @Override
        public Feed getItem(int position) {
            return feeds.get(position);
        }

        @Override
        public long getItemId(int position) {
            return feeds.get(position).id;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            FeedListItemViewHolder viewHolder;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.feed_list_item2, parent, false);
                viewHolder = new FeedListItemViewHolder(NewsFeedFragment.this, view);
                view.setTag(viewHolder);
            }
            viewHolder = (FeedListItemViewHolder) view.getTag();
            LogUtils.d("getView at position " + position + ", feed is " + feeds.get(position));
            viewHolder.bindData(feeds.get(position));
            return view;
        }
    }

    List<Feed> feeds = new ArrayList<>();

    private void loadFeeds(final int start) {
        String url = getFeedUrl(start);
        GsonRequest<FeedListResponse> request = new GsonRequest<FeedListResponse>(url,
                Request.Method.GET,
                FeedListResponse.class, true, null, new Response.Listener<FeedListResponse>() {
            @Override
            public void onResponse(FeedListResponse response) {
                if (response.ret) {
                    ArrayList<ContentValues> values = new ArrayList<ContentValues>();
                    LogUtils.d("loadFeeds, feeds size is " + response.data.length);
                    if (start == 0) {
                        feeds.clear();
                    }
                    if (response.data != null) {
                        feeds.addAll(Arrays.asList(response.data));
                    }
                    mAdapter.notifyDataSetChanged();
                }
                finishLoading();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                finishLoading();
                Utils.showToast(R.string.generic_network_error);
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private String getFeedUrl(int start) {
        switch (mFeedType) {
            case TYPE_HOT:
                return NetworkConstants.NEWS_HOT_URL + "?" + "start=" + start + "&limit="
                        + Constants.PAGE_SIZE;
            case TYPE_TIMELINE:
                return String.format(NetworkConstants.NEWS_TIMELINE_URL,
                        Settings.getUid()) + "?" + "start=" + start + "&limit="
                        + Constants.PAGE_SIZE;
            case TYPE_MINE:
                return String.format(NetworkConstants.FORWARD_URL,
                        Settings.getUid()) + "?" + "start=" + start + "&limit="
                        + Constants.PAGE_SIZE;
            case TYPE_OTHERS:
                return String.format(NetworkConstants.MY_FEED_URL, mUserId) + "?" + "start=" + start
                        + "&limit=" + Constants.PAGE_SIZE;
            default:
                return null;
        }
    }

}
